from django.shortcuts import redirect
from django.urls import reverse
 
 
class GroupPermissionMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
 
    def __call__(self, request):
        # 在每个请求之前进行组权限判断
        if not self.check_group_permission(request):
            return redirect(reverse('需要返回的url地址(一般是登录页，自行决定)'))
 
        response = self.get_response(request)
        return response
 
    def check_group_permission(self, request):
        # 获取当前请求的用户对象
        user = request.user
        # 获取当前请求的路径
        path = request.path
 
        # 设置需要进行限制访问的路径列表和对应的组
        restricted_paths = {
            'followprice/<str:module>/': '产品跟价',
            # 拿刚才创建的group1来举例

        }
 
        # 检查用户是否属于指定组，并判断是否允许访问特定页面
        for restricted_path, restricted_group in restricted_paths.items():
            if restricted_path in path and not user.groups.filter(name=restricted_group).exists():
                return False
 
        return True